<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">统一身份登录</div>
    <!-- <div class="login-form-sub-title">{{ $t('login.form.title') }}</div> -->
    <span class="login-form-error-msg">{{ errorMessage }}</span>
    <a-form
      ref="loginForm"
      :model="userInfo"
      class="login-form"
      layout="vertical"
      @submit="handleSubmit"
    >
      <a-form-item
        label="用户名"
        field="account"
        :validate-trigger="['change', 'blur']"
        hide-asterisk
      >
        <a-input v-model="userInfo.account" placeholder="请输入用户名">
          <template #prefix>
            <icon-user />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        label="密码"
        field="password"
        :rules="[{ required: true, message: $t('login.form.password.errMsg') }]"
        :validate-trigger="['change', 'blur']"
        hide-asterisk
      >
        <a-input-password
          v-model="userInfo.password"
          placeholder="请输入密码"
          allow-clear
        >
          <template #prefix>
            <icon-lock />
          </template>
        </a-input-password>
      </a-form-item>
      <a-space :size="16" direction="vertical">
        <div class="login-form-password-actions">
          <a-checkbox
            checked="rememberPassword"
            :model-value="loginConfig.rememberPassword"
            @change="setRememberPassword as any"
          >
            {{ $t('login.form.rememberPassword') }}
          </a-checkbox>
          <a-link>{{ $t('login.form.forgetPassword') }}</a-link>
        </div>
        <a-button type="primary" html-type="submit" long :loading="loading">
          {{ $t('login.form.login') }}
        </a-button>
        <!-- <a-button type="text" long class="login-form-register-btn">
          {{ $t('login.form.register') }}
        </a-button> -->
      </a-space>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { useRouter } from 'vue-router';
  import { Notification } from '@arco-design/web-vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import { useI18n } from 'vue-i18n';
  import { useStorage } from '@vueuse/core';
  // import { useUserStore } from '@/store';
  import useLoading from '@/hooks/loading';
  import { LoginData, login, getUserPermissions } from '@/api/user';
  import {
    setToken,
    setListNumber,
    setName,
    setUserJob,
    setUserUnits,
    setUserUnitsNumber,
    clearToken,
    clearListNumber,
    clearName,
    clearUserJob,
    clearUserUnits,
    clearUserUnitsNumber,
  } from '@/utils/auth';

  const router = useRouter();
  const { t } = useI18n();
  const errorMessage = ref('');
  const { loading, setLoading } = useLoading();
  // const userStore = useUserStore();

  const loginConfig = useStorage('login-config', {
    rememberPassword: true,
    account: '', // 演示默认值
    password: '', // demo default value
  });
  const userInfo = reactive({
    account: loginConfig.value.account,
    password: loginConfig.value.password,
  });

  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (loading.value) return;
    if (!errors) {
      setLoading(true);
      try {
        const res: any = await login(values as LoginData);
        if (res.retCode === '200') {
          setToken('admin');
          setListNumber(res.responseBody);
          setName(res.responseBody.account);
          setUserJob(res.responseBody.empinfoid);
          setUserUnits(
            res.responseBody.empinfoDTOList[0].departmentDTOList[0].text
          );
          setUserUnitsNumber(res.responseBody.empinfoDTOList[0].departid);
          const { redirect, ...othersQuery } = router.currentRoute.value.query;
          //  获取权限
          const data = await getUserPermissions({
            account: res.responseBody.empinfoid,
          });
          // 判断是否有当前页面权限
          if (redirect && data.some((item: any) => item.name === redirect)) {
            router
              .push({
                name: redirect as string,
                query: {
                  ...othersQuery,
                  redirect,
                },
              })
              .then(() => {
                window.location.reload();
              });
          } else {
            router
              .push({
                name: '工作台',
                query: {
                  ...othersQuery,
                },
              })
              .then(() => {
                window.location.reload();
              });
          }
          Notification.success({
            title: '成功',
            content: t('login.form.login.success'),
            closable: true,
          });
          const { rememberPassword } = loginConfig.value;
          const { account, password } = values;
          // 实际生产环境需要进行加密存储。
          // The actual production environment requires encrypted storage.
          loginConfig.value.account = rememberPassword ? account : '';
          loginConfig.value.password = rememberPassword ? password : '';
        } else {
          Notification.error({
            title: '失败',
            content: res.message,
            closable: true,
          });
        }
      } catch (err) {
        clearToken();
        clearListNumber();
        clearName();
        clearUserJob();
        clearUserUnits();
        clearUserUnitsNumber();
        throw err;
      } finally {
        setLoading(false);
      }
    }
  };
  const setRememberPassword = (value: boolean) => {
    loginConfig.value.rememberPassword = value;
  };
</script>

<style lang="less" scoped>
  .login-form {
    // &-wrapper {
    // }
    &-title {
      margin-bottom: 60px;
      color: var(--color-text-1);
      font-weight: bold;
      font-size: 22px;
      // line-height: 32px;
    }

    &-sub-title {
      color: var(--color-text-3);
      font-size: 16px;
      line-height: 24px;
    }

    &-error-msg {
      height: 32px;
      color: rgb(var(--red-6));
      line-height: 32px;
    }

    &-password-actions {
      display: flex;
      justify-content: space-between;
    }

    &-register-btn {
      color: var(--color-text-3) !important;
    }
  }
</style>
